﻿Public Class optionsForm
    Private Async Sub saveButton_Click(sender As Object, e As EventArgs) Handles saveButton.Click
        ' Save the settings
        ' Confirm when removing a folder from the list
        AppSettings.ConfirmWhenDeletingFolder = removeItemConfrimCheckBox.Checked

        ' Confirm before running cleaner
        If Not AppSettings.ErrorDetected Then
            AppSettings.ConfirmBeforeRunningCleaner = cleanupConfirmCheckBox.Checked
        End If

        ' Overwrite method
        If Not AppSettings.ErrorDetected Then
            If permanentlyDeleteRadioButton.Checked Then
                AppSettings.OverwriteMethod = 0
            Else
                AppSettings.OverwriteMethod = 1
            End If
        End If

        'Overwrite type
        If Not AppSettings.ErrorDetected Then
            AppSettings.OverwriteType = overwriteTypeComboBox.SelectedIndex
        End If

        ' Automatically scan for installed apps at application startup
        If Not AppSettings.ErrorDetected Then
            AppSettings.ScanInstalledAppsAtStartup = scanInstalledAppsCheckBox.Checked
        End If

        ' Refresh folders sizes before running cleaner
        If Not AppSettings.ErrorDetected Then
            AppSettings.RefreshSizeBeforeRunningCleaner = refreshSizeBeforeCleanupCheckBox.Checked
        End If

        ' Create a backup file
        If Not AppSettings.ErrorDetected Then
            Await Task.Run(Sub()
                               My.Computer.FileSystem.CopyFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & _
                                           "\Modern UI Apps Cleaner\config.dat", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & _
                                           "\Modern UI Apps Cleaner\config.bak", True)
                           End Sub)
        End If

        Me.Close()
    End Sub

    Private Sub cancel_Button_Click(sender As Object, e As EventArgs) Handles cancel_Button.Click
        Me.Close()
    End Sub

    Private Sub optionsForm_Load(sender As Object, e As EventArgs) Handles Me.Load
        ' Retrieve settings
        ' Confirm when removing a folder from the list
        If Not AppSettings.ConfirmWhenDeletingFolder Then
            removeItemConfrimCheckBox.Checked = False
        Else
            removeItemConfrimCheckBox.Checked = True
        End If

        ' Confirm before running cleaner
        If AppSettings.ErrorDetected AndAlso Not AppSettings.ConfirmBeforeRunningCleaner Then
            cleanupConfirmCheckBox.Checked = True
        Else
            cleanupConfirmCheckBox.Checked = False
        End If

        ' Overwrite method
        If AppSettings.ErrorDetected Or AppSettings.OverwriteMethod = 1 Then
            reclycleRadioButton.Checked = True
        Else
            permanentlyDeleteRadioButton.Checked = True
        End If

        'Overwrite type
        If Not AppSettings.ErrorDetected Then
            overwriteTypeComboBox.SelectedIndex = AppSettings.OverwriteType
        Else
            overwriteTypeComboBox.SelectedIndex = 1
        End If

        ' Refresh folders sizes before running cleaner
        If Not AppSettings.ErrorDetected Then
            refreshSizeBeforeCleanupCheckBox.Checked = AppSettings.RefreshSizeBeforeRunningCleaner
        Else
            refreshSizeBeforeCleanupCheckBox.Checked = True
        End If

        ' Automatically scan for installed apps at application startup
        If Not My.Computer.Info.OSFullName.Contains("Windows 8") Or _
            Not My.Computer.Info.OSFullName.Contains("Windows 8.1") Then

            scanInstalledAppsCheckBox.Checked = False
            scanInstalledAppsCheckBox.Enabled = False
        Else
            If AppSettings.ErrorDetected Or Not AppSettings.ScanInstalledAppsAtStartup Then
                scanInstalledAppsCheckBox.Checked = False
            Else
                scanInstalledAppsCheckBox.Checked = True
            End If
        End If

        ' Hide the export confirmation label
        If exportDoneLabel.Visible Then
            exportDoneLabel.Visible = False
        End If
    End Sub

    Private Async Sub importButton_Click(sender As Object, e As EventArgs) Handles importButton.Click
        ' Initialize a new OpenFileDialog to let the user browse for the settings file
        Using openFile As New OpenFileDialog() With {.AddExtension = True, .AutoUpgradeEnabled = True, .CheckFileExists = True, .CheckPathExists = True, .DefaultExt = ".dat", _
                                    .DereferenceLinks = True, .Filter = "Configuration file (*.dat)|*.dat", .Multiselect = False, .Title = "Choose the configuration file"}

            ' Process the file
            ' If the user selected a valid file and confirmed the overwrite, then copy it to the settings folder and create a backup
            If openFile.ShowDialog() = Windows.Forms.DialogResult.OK AndAlso Await CheckIfValidSettings() _
                AndAlso MessageBox.Show("Are you sure you want to overwrite the current settings?", _
                                        "Confirm overwrite", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                Try
                    Await Task.Run(Sub()
                                       My.Computer.FileSystem.CopyFile(openFile.FileName, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Modern UI Apps Cleaner\config.dat", True)

                                       My.Computer.FileSystem.CopyFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & _
                                                   "\Modern UI Apps Cleaner\config.dat", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & _
                                                   "\Modern UI Apps Cleaner\config.bak", True)
                                   End Sub)
                    ' Show a MessageBox
                    MessageBox.Show("Successfully imported settings!", "Import/Export settings", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Catch ex As Exception
                    ' If any other exception occurred, show an error message
                    If ex.InnerException IsNot Nothing Then
                        MessageBox.Show("Error while saving settings: " & ex.Message + ControlChars.CrLf + ControlChars.CrLf + _
                                        ex.InnerException.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Else
                        MessageBox.Show("Error while saving settings: " & ex.Message, _
                                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    End If
                Finally
                    importPathLabel.Text = "Choose a XML settings file"

                    Me.Close()
                End Try
            Else
                importPathLabel.Text = "File is not valid or operation was canceled. Please choose a XML settings file"
            End If
        End Using
    End Sub

    Private Async Sub exportButton_Click(sender As Object, e As EventArgs) Handles exportButton.Click
        ' Initialize the FolderBrowserDialog to let the user browse for the folder containing the settings file
        Using folderBrowser As New FolderBrowserDialog() With {.Description = "Choose the folder that contains the settings file", .ShowNewFolderButton = False}
            ' Process the folder
            If folderBrowser.ShowDialog() = Windows.Forms.DialogResult.OK Then
                ' If the file doesn't already exist, copy it to the selected folder
                If Not My.Computer.FileSystem.FileExists(folderBrowser.SelectedPath & "\muiappscleaner_config.dat") Then
                    Await Task.Run(Sub()
                                       My.Computer.FileSystem.CopyFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & _
                                                   "\Modern UI Apps Cleaner\config.dat", folderBrowser.SelectedPath & "\muiappscleaner_config.dat", False)
                                   End Sub)

                    ' Show the export completed status label
                    If Not exportDoneLabel.Visible Then
                        exportDoneLabel.Visible = True
                    End If
                Else
                    ' If the file already exists, ask the user to overwrite.
                    If MessageBox.Show("File already exists. Do you want to overwrite?", _
                                       "Confirm overwrite", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                        Await Task.Run(Sub()
                                           My.Computer.FileSystem.CopyFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & _
                                                       "\Modern UI Apps Cleaner\config.dat", folderBrowser.SelectedPath & "\muiappscleaner_config.dat", True)
                                       End Sub)

                        ' Show the export completed status label
                        If Not exportDoneLabel.Visible Then
                            exportDoneLabel.Visible = True
                        End If
                    Else
                        ' Show a MessageBox
                        MessageBox.Show("Cannot export settings: user refused to overwrite existing file", "Import/Export settings", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                    End If
                End If
                ' End check if file exists

            End If
            ' End process folder

        End Using
        ' End FolderBrowserDialog
    End Sub
End Class